package com.atguigu.vod.service.impl;


import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.VideoService;
import com.atguigu.vod.utils.ConstantYmlUtils;
import com.atguigu.vod.utils.InitVodClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {
    @Override
    public String upLoadVideo(MultipartFile file) {

        try {
            //文件转换为输入流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String title = filename.substring(0, filename.lastIndexOf("."));

//            System.out.println("title: "+ title + "filename" + filename);


//        UploadFileStreamRequest request = new UploadFileStreamRequest();
            UploadStreamRequest request = new UploadStreamRequest(ConstantYmlUtils.ACCESS_KEY_ID, ConstantYmlUtils.ACCESS_KEY_SECRET, title, filename, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if (response.isSuccess()){
                videoId = response.getVideoId();
            }else {

               videoId = response.getVideoId();
            }
            return videoId;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Boolean removeVideoBatch(List VideoIdList) {

        DefaultAcsClient client = InitVodClient.initVodClient(ConstantYmlUtils.ACCESS_KEY_ID, ConstantYmlUtils.ACCESS_KEY_SECRET);

   //    创建删除对象
        DeleteVideoRequest request = new DeleteVideoRequest();

        //VideoIdList 转换为1,2,3
        String videoIds = StringUtils.join(VideoIdList.toArray(), ",");

        request.setVideoIds(videoIds);

        try {
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }


        return null;
    }


}
